package org.jeecg.modules.demo.ch.exception;

import cn.hutool.core.util.StrUtil;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.regex.Pattern;

public class Assert {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws CustomException 校验不通过，则报RRException异常
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws CustomException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage());
            }
            throw new CustomException(msg.toString());
        }
    }

    public static void isBlank(String str, String message) throws CustomException {
        if (StrUtil.isBlank(str)) {
            throw new CustomException(message);
        }
    }

    public static void isNull(Object object, String message) throws CustomException {
        if (object == null) {
            throw new CustomException(message);
        }
    }

    public static void isMatchRex(String string, String pattern, String message) throws CustomException {
        Boolean res = Pattern.matches(pattern, string);
        if (res.equals(Boolean.FALSE)) {
            throw new CustomException(message);
        }
    }
}
